<?php

namespace App\Admin\Controllers;

use App\Models\Order;
use App\Http\Controllers\Controller;
use App\Models\OrderPhone;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Layout\Content;
use App\Admin\Extensions\CheckRecheckConfirmed;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use App\Http\Repositories\SignatureHelper;
use Illuminate\Support\Facades\DB;

class RecheckOrdersController extends Controller
{
    use HasResourceActions;

    //列表
    public function index(Content $content)
    {
        return Admin::content(function (Content $content) {
            $content->header('复审订单列表');
            $content->body($this->grid());
        });
    }

    //查看详情
    public function show($id, Content $content)
    {
        return $content
            ->header('复审订单')
            ->description('详情')
            ->body($this->detail($id));
    }

    //订单列表
    protected function grid()
    {
        return Admin::grid(Order::class, function (Grid $grid) {
            $grid->id('ID')->sortable();
            $grid->user()->name('下单用户');
            $grid->order_no('订单编号');
            $grid->information('商品信息');
            $grid->amount('下单数量');
            $grid->create_at('下单时间');
            $grid->logistics_company('物流公司');
            $grid->tracking_number('物流单号');
            $grid->is_delivery('是否发货')->display(function ($value) {
                return ($value==1) ? '已发货' : '未发货';
            });
            $grid->is_receiving('是否收货')->display(function ($value) {
                return ($value==1) ? '已收货' : '未收货';
            });

            $grid->model()->orderBy('create_at', 'desc');

            $grid->model()->where('is_receiving', '1');
            $grid->model()->where('is_trial', '1');
            $grid->model()->where('is_recheck', '1');
            $grid->model()->where('is_recheck_confirmed', '0');

            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();

                // append一个操作
                $actions->append(new CheckRecheckConfirmed($actions->getKey()));
            });

            $grid->tools(function ($tools) {
                // 禁用批量删除按钮
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->filter(function($filter){
                // 去掉默认的id过滤器
                $filter->disableIdFilter();

                // 在这里添加字段过滤器
                $filter->column(1/3, function ($filter) {
                    $filter->like('order_no', '订单编号');
                });
                $filter->column(1/3, function ($filter) {
                    $filter->like('tracking_number', '物流单号');
                });
            });

            $grid->disableCreateButton();

            $grid->disableRowSelector();

            //禁用导出按钮
            $grid->disableExport();
        });
    }


    /**
     * 订单详情
     *
     * @param mixed   $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Order::findOrFail($id));

        $show->id('ID')->sortable();
        $show->order_no('订单编号');
        $show->information('商品信息');
        $show->amount('下单数量');
        $show->create_at('下单时间');
        $show->logistics_company('物流公司');
        $show->tracking_number('物流单号');
        $show->is_delivery('是否发货')->as(function ($value) {
            return ($value==1) ? '已发货' : '未发货';
        });
        $show->picture('商品图片')->unescape()->as(function ($value) {
            $img = '';
            if(!empty($value)) {
                $value = explode(',', $value);
                foreach ($value as $k => $v) {
                    $img .= "<img src='{$v}' style='width: 200px;height: 200px;'/>";
                }
            }
            return $img;
        });

        $show->user('用户信息', function ($user) {
            $user->name('用户名称');
            $user->phone('用户电话');

            $user->panel()->tools(function ($tools) {
                $tools->disableDelete();
                $tools->disableEdit();
                $tools->disableList();
            });
        });

        $show->phone('子订单', function ($phone) {
            $phone->resource('/admin/order_phone');

            $phone->id('ID');
//            $phone->title('简介');
            $phone->phone_model('手机型号');
            $phone->note('备注');
            $phone->imei('IMEI码');
            $phone->level('等级');
            $phone->code('机器标码');
            $phone->price('价格');
            $phone->logistics_company('已退回订单选择物流公司');
            $phone->tracking_number('已退回订单选择物流单号');

            $phone->disableExport();
            $phone->disableRowSelector();
            $phone->disableCreateButton();


            $phone->actions(function ($actions) {
                $actions->disableView();
            });
        });

        $show->panel()->tools(function ($tools) {
            $tools->disableDelete();
            $tools->disableEdit();
        });

        return $show;
    }

    //复审确认
    public function RecheckConfirmed(Request $request)
    {
        $id = $request->post('id');

        //查询数据
        $info = DB::table('orders')->where('id', $id)->first();

        $user = DB::table('users')->where('id', $info->u_id)->first();

        $phone = DB::table('order_phones')->where('o_id', $info->id)->get();
        if(!empty($phone)) {
            foreach ($phone as $k => $v) {
                if(empty($v->price)) {
                    return ['code' => false, 'msg' => '复审确认前，所有子订单价格不能为空，请重新确认子订单信息'];
                }
            }
        }


        $update['is_recheck_confirmed'] = '1';

        $res = Order::where('id', $id)->update($update);

        OrderPhone::where('o_id', $id)->update(['is_confirm' => 1]);

        if(!$res) {
            return ['code' => 'false', 'msg' => '修改失败'];
        }

        if(Config::get('system.environment') == 'production') {
            $templateCode = 'SMS_166777892';
            //调取短信通道
            $templateParam = array(
                'name' => (empty($user->name)) ? $user->phone : $user->name,
                'order_no' => $info->order_no,
            );

            $aliYun = $this->aliYun($user->phone, $templateCode, $templateParam);
            if ($aliYun->Code != 'OK') {
                return ['code' => 0, 'msg' => $aliYun->Message];
            }
            $content = DB::table('message_templates')->where('template_code', $templateCode)->value('content');
            $message = str_replace('{name}', (empty($user->name)) ? $user->phone : $user->name, $content);
            $message = str_replace('{order_no}', $info->order_no, $message);
            $inset = [
                'mobile' => $user->phone,
                'message_template_id' => $templateCode,
                'code' => '',
                'message' => $message,
                'send_at' =>date('Y-m-d H:i:s', time()),
                'overdue_at' =>date('Y-m-d H:i:s', time()+300),
                'is_use' => '1',
                'type' => '1'
            ];
            DB::table('messages')->insert($inset);
        }

        return ['code' => 'true', 'msg' => '修改成功'];
    }

    /**
     * 发送短信
     *
     * @return bool|\stdClass
     */
    public function aliYun($mobile, $templateCode, $templateParam) {
        $params = array ();

        $aliYun = Config::get("sms.aliYun");

        // *** 需用户填写部分 ***
        // 是否启用https
        $security = false;

        // 获取用户AK信息
        $accessKeyId = $aliYun['accessKeyId'];
        $accessKeySecret = $aliYun['accessKeySecret'];

        // 短信发送手机号
        $params["PhoneNumbers"] = $mobile;

        // 短信签名
        $params["SignName"] = $aliYun['SignName'];

        // 模板短信code
        $params["TemplateCode"] = $templateCode;

        if(!empty($templateParam)) {
            // 模板变量
            $params['TemplateParam'] = $templateParam;
        }

        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }

        //此处可能会抛出异常，注意catch
        $sign = new SignatureHelper();
        $content = $sign->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            )),
            $security
        );

        return $content;
    }
}
